#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#include "serveur.h"
#include "requetes.h"
#include "structClient.h"
void winstart(void){
#ifdef WIN32
    WSADATA wsa;
    int err = WSAStartup(MAKEWORD(2, 2), &wsa);
    if(err < 0)
    {
        puts("WSAStartup failed !");
        exit(EXIT_FAILURE);
    }
#endif
}

void winstop(void){
#ifdef WIN32
    WSACleanup();
#endif
}

int debutConnexion(void){
    SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
    SOCKADDR_IN sin = { 0 };

    if(sock == INVALID_SOCKET)
    {
        perror("socket()");
        exit(errno);
    }

    sin.sin_addr.s_addr = htonl(INADDR_ANY);
    sin.sin_port = htons(PORT);
    sin.sin_family = AF_INET;

    if(bind(sock,(SOCKADDR *) &sin, sizeof sin) == SOCKET_ERROR)
    {
        perror("bind()");
        exit(errno);
    }

    if(listen(sock, MAX_CLIENTS) == SOCKET_ERROR)
    {
        perror("listen()");
        exit(errno);
    }

    return sock;
}

void finConnexion(int sock){
    closesocket(sock);
}

int lireTexte(SOCKET sock, char *buffer){
    int n = 0;

    if((n = recv(sock, buffer, TAILLE_BUFFER - 1, 0)) < 0)
    {
        perror("recv()");
        /* if recv error we disonnect the client */
        n = 0;
    }

    buffer[n] = 0;

    return n;
}

void ecrireTexte(SOCKET sock, const char *buffer){
    if(send(sock, buffer, strlen(buffer), 0) < 0)
    {
        perror("send()");
        exit(errno);
    }
}

int lireBinaire(SOCKET sock, void *buffer, int taille){

    int err = recv(sock, buffer, taille, 0);

    printf("j'ai recu %d\n", err);
    if ( 0 > err ){
        fprintf(stderr, "erreur recv\n");
    }
    else
    {
    }

    
    return err;
}

int ecrireBinaire(SOCKET sock, void * buffer, int taille)
{
    int err =send(sock, buffer, taille, 0);
    if ( 0 == err ){
        fprintf(stderr, "erreur recv\n");
    }
    return err;

}


